<?php

namespace app\console\controller;

namespace app\console\controller;

use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\Order as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;

class Tyre extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'clearCache' => ['only'],
    ];


    /**
     * 广告位列表
     */
    public function index()
    {

        $param = Request::instance()->param();
        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10
        $auding_status = Session::get('auding_status');
        $where = [];
        if($auding_status == 1){
            $where['o.shop_id'] = ['eq',\session('shop_id')];
        }
        $where['o.order_type'] = ['eq', 2];
        $where['o.status'] = ['in','50,1,6,5,4,10,11,12,20'];
        if (!empty($param['status'])){
            if($param['status'] == 2){
                $where['o.status'] = ['in', $this->status];
            }else{
                //$where['o.auding_status'] = ['eq',2];
                $where['o.status'] = ['eq', $param['status']];
            }
        }
        if (!empty($param['auding_status'])){
            $where['o.auding_status'] = ['eq', $param['auding_status']];
            $where['o.is_free_order'] = ['eq', 2];
        }
        if (!empty($param['finance_order'])) $where['o.finance_order'] = ['eq', $param['finance_order']];
        if (!empty($param['order_online'])) $where['o.order_online'] = ['eq', $param['order_online']];
        if (!empty($param['shop_id'])) $where['o.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['is_certification'])) $where['m.is_certification'] = ['eq', $param['is_certification']];
        if (!empty($param['single_parent_id'])) $where['single_parent_id|single_id'] = ['eq', $param['single_parent_id']];
        if (!empty($param['title'])){
            $where['o.username|o.shop_order_number|o.order_number|m.car_number|o.car_number'] = ['like', '%'.$param['title'].'%'];//|sew.cat_name|sewa.cat_name
        }
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        if(session('role_id') != 1){
            $where['o.is_delete'] = ['eq', 1];
        }

        if (!empty($param['auding_statusf'])) $where['o.auding_statusf'] = ['eq', $param['auding_statusf']];
        if (!empty($param['auding_status1f'])) $where['o.auding_status1f'] = ['eq', $param['auding_status1f']];
        if (!empty($param['auding_status2f'])) $where['o.auding_status2f'] = ['eq', $param['auding_status2f']];
        if (!empty($param['auding_status3f'])) $where['o.auding_status3f'] = ['eq', $param['auding_status3f']];
        if (!empty($param['auding_statusq'])) $where['o.auding_statusq'] = ['eq', $param['auding_statusq']];
        if (!empty($param['auding_status1q'])) $where['o.auding_status1q'] = ['eq', $param['auding_status1q']];
        if (!empty($param['auding_status2q'])) $where['o.auding_status2q'] = ['eq', $param['auding_status2q']];
        if (!empty($param['auding_status3q'])) $where['o.auding_status3q'] = ['eq', $param['auding_status3q']];
        if (!empty($param['take_tyre'])) $where['o.take_tyre'] = ['eq', $param['take_tyre']];

        $shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');
        $auding_status = Session::get('auding_status');

        $param = Request::instance()->param();

        if($auding_status == 1){
            $data = Model::alias('o')->where('single_id',11)
                ->join('member m','o.member_id = m.id')
                ->field('o.*,m.username,m.nickname,m.car_number m_car_number')
                ->order('id','desc')
                ->where('shop_id',session('shop_id'))
                ->where($where)
                ->paginate(10,false,['query' => $param])->each(function($item,$key){
                    if(session('role_id') != 1){
                        $item->username = hideStr($item->username,1,6);
                    }
                });
        }else{
            $data = Model::alias('o')->where('single_id',11)
                ->join('member m','o.member_id = m.id')
                ->field('o.*,m.username,m.nickname,m.car_number m_car_number')
                ->order('id','desc')
                ->where($where)
                ->paginate(10,false,['query' => $param])->each(function($item,$key){
                    if(session('role_id') == 17){
                        $item->username = hideStr($item->username,1,6);
                    }
                });
        }
        $shop_list = Db::name('shop s')->field('id,shop_title')->select();

//        halt($data);
        $this->assign('shop_list',$shop_list);
        return $this->fetch('', [
            'data' => $data,

        ]);
    }


    public function daochu(){
        $auding_status = Session::get('auding_status');
        $where = [];
        $param = Request::instance()->param();
        if(!empty($param['title'])) $where['o.order_number|m.username'] = ['like','%'.$param['title'].'%'];

        if($auding_status == 1){
            $data = Model::alias('o')->where('single_id',11)
                ->join('member m','o.member_id = m.id')
                ->field('o.*,m.username,m.nickname')
                ->order('id','desc')
                ->where($where)
                ->where('shop_id',session('shop_id'))
                ->paginate(10000)->each(function($item,$key){
                    $item->shop_id = db('shop')->where('id',$item['shop_id'])->value('shop_title');
                    if(session('role_id') != 1){
                        $item->username = hideStr($item->username,1,6);
                    }
                    switch ($item->status){
                        case 50;
                            $item->status = '等待沟通';
                        break;
                        case 1;
                            $item->status = '代付款';
                            break;
                        case 6;
                            $item->status = '进行中';
                            break;
                        case 5;
                            $item->status = '待评价';
                            break;
                        case 4;
                            $item->status = '已完成';
                            break;
                        case 10;
                            $item->status = '退款中';
                            break;
                        case 11;
                            $item->status = '退款成功';
                            break;
                        case 12;
                            $item->status = '退款失败';
                            break;
                    }
                });
        }else{
            $data = Model::alias('o')->where('single_id',11)
                ->join('member m','o.member_id = m.id')
                ->field('o.*,m.username,m.nickname')
                ->order('id','desc')
                ->where($where)
                ->paginate(10000)->each(function($item,$key){
                    $item->shop_id = db('shop')->where('id',$item->shop_id)->value('shop_title');
                    switch ($item->status){
                        case 50;
                            $item->status = '等待沟通';
                            break;
                        case 1;
                            $item->status = '代付款';
                            break;
                        case 6;
                            $item->status = '进行中';
                            break;
                        case 5;
                            $item->status = '待评价';
                            break;
                        case 4;
                            $item->status = '已完成';
                            break;
                        case 10;
                            $item->status = '退款中';
                            break;
                        case 11;
                            $item->status = '退款成功';
                            break;
                        case 12;
                            $item->status = '退款失败';
                            break;
                    }
                    switch ($item->take_tyre){
                        case 1;
                            $item->take_tyre_title = '已寄存';
                            break;
                        case 2;
                            $item->take_tyre_title = '已取走';
                            break;
                        case 3;
                            $item->take_tyre_title = '确认前台寄存';
                            break;
                        case 4;
                            $item->take_tyre_title = '确认前台取走';
                            break;
                        case 5;
                            $item->take_tyre_title = '等待审核';
                            break;
                    }
                });
        }
        $this->push_coupon($data);
    }

    public function push_coupon($data,$name = '轮胎寄存订单')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'id')
            ->setCellValue('B1', '订单号')
            ->setCellValue('C1', '寄存金额')
            ->setCellValue('D1', '用户账号')
            ->setCellValue('E1', '寄存时间')
            ->setCellValue('F1', '寄存门店')
            ->setCellValue('G1', '订单状态')
            ->setCellValue('H1', '是否取走')
        ;
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['order_number'])
                ->setCellValue('C' . $num, $v['amount'])
                ->setCellValue('D' . $num, $v['username'])
                ->setCellValue('E' . $num, $v['start_time'].'-'.$v['end_time'])
                ->setCellValue('F' . $num, $v['shop_id'])
                ->setCellValue('G' . $num, $v['status'])
                ->setCellValue('H' . $num, $v['take_tyre_title'])

            ;

            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('轮胎寄存订单');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {


        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();



//            // 验证
//            $validate = Loader::validate('AdType');
//            if (!$validate->scene('create')->check($data)) fail($validate->getError());
           $data['take_tyre'] = 5;//订单待审核
            // 提交数据
            $member_id = Db::name('member')->where('username',$data['username'])->value('id');
            $data['car_number'] = (new \app\index\controller\GiftOrder())->car_number('',$member_id);
            if(\session('auding_status') == 1 && empty($data['explain'])){
                //门店
                fail('门店必须填写备注');
            }
            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
//                if($data['status'] == 6){
//                    $cont = '免费寄存';
//                }else{
//                    $cont = '付费寄存,金额'.number_format($data['amount'],2).'元';
//                }
//
//                $member_id =Db::name('member')->where('username',$data['username'])->value('id');
//                (new \app\index\controller\MemberMessage())->jpushMessage($member_id,'您的轮胎寄存成功,'.$cont,'寄存区间:'.$data['interval_timer'],3);

//                (new \app\index\controller\MemberMessage())->jpushMessage('轮胎寄存成功',35,5);
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }
        $shop_id = 0;
        $auding_status = Session::get('auding_status');
        if($auding_status == 1){
            $shop_id = \session('shop_id');
        }
        return $this->fetch('create', ['shop_id' => $shop_id

        ]);

    }


    /**
     * 广告位编辑$shop_id = \session('shop_id');
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            // 验证
           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);


            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $item = Model::get($id);
        $shop_id = 0;
        $auding_status = Session::get('auding_status');
        if($auding_status == 1){
            $shop_id = \session('shop_id');
        }

        return $this->fetch('create', [
            'shop_id' => $shop_id,
            'item' => $item
        ]);
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
            auding_status($id,'title');
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }





    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            (new AdTypeModel)->where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('AdType/index'));
    }

    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}